#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "lexer.h"

#define SL_Version 0.1.0
#define SL_Temp(x) "slang 版本号 "#x
#define SL_Version_String(x) SL_Temp(x)

void printUsage()
{
    printf("usage:slang [-opition] [filename]\n");
    printf("[opition]\n");
    printf("\t-l 显示词法分析的记号流.\n");
    printf("\t-p 显示语法分析的语句流.\n");
    printf("\t--versin 显示当前版本.\n");
    printf("\t--help 显示帮助信息.\n");
}

void printVersion()
{
    printf( "%s\n",SL_Version_String(SL_Version) );
}

typedef void (*Command)(FILE *fl);

static void printLexer(FILE *fl)
{
	assert(fl);
	Lexer *self;
	self=createLexer();
	initLexerByFile(self,fl);
	Token *token;
	token=readToken(self);
	while(token->type!=TK_END){
		printToken(token);
		token=readToken(self);
	}
	free(self->buffer);
	free(self);
}

static void printParser(FILE *fl)
{
	assert(fl);
	printf("该功能未实现\n");
}

static void printBin(FILE *fl)
{
	assert(fl);
	printf("该功能未实现\n");
}

Command parserOpinion(char *buffer)
{
    if(buffer[0]=='-'){
        char *word=buffer+1;
        if(strcmp(word,"version")==0){
            printVersion();
            exit(0);
        }else if(strcmp(word,"help")==0){
            printUsage();
            exit(0);
        }
    }
    //表示输出lexer信息
    if(buffer[0]=='l'){
        return printLexer;
    }else if(buffer[0]=='p'){//表示输出parser功能
        return printParser;
    }else{
        printf("未知的命令-%s\n",buffer);
        printUsage();
        exit(1);
    }
}

int main(int argc, char **argv)
{
	if(argc<2){
        printUsage();
        return 0;
    }
    int filepos;
    char *buffer;
    buffer=argv[1];
	Command command;
    if(buffer[0]=='-'){
        command=parserOpinion(buffer+1);
		filepos=2;
    }else{
		command=0;
		filepos=1;
	}
    //printf("%s\n",argv[1]);
    FILE *fl;
	fl=fopen(argv[filepos],"rt");
    if(fl==0){
        printf("无法打开文件%s,请检查文件是否存在或者是否拥有足够的权限.",argv[filepos]);
        return 1;
    }
	if(command==0){
		printBin(fl);
	}else{
		command(fl);
	}
	return 0;
}
